import React, { Component } from 'react'
import styles from './index.module.scss'
import { Flex, PickerView } from 'antd-mobile'
import classNames from 'classnames'
import { getHouseCondition } from '../../api/filter'
import { getCurrentCity } from '../../utils/city'
import FilterFooter from '../FilterFooter'
import { Spring } from 'react-spring/renderprops'

export default class Filter extends Component {
  constructor () {
    super()

    this.state = {
      openType: '', // 点击或是打开的类型
      // 标题选中（决定是否高亮显示）
      selectedTypeTitle: {
        area: false,
        mode: false,
        price: false,
        more: false
      },
      // 最终的数据，并且该数据将来要传递给父组件(HouseList)
      // 只有当我们点击了确定之后才能更改这个selectValue的数据，其它情况下不允许该
      selectValue: {
        area: ['area', 'null'],
        mode: ['null'],
        price: ['null'],
        more: []
      },
      // 为区域、方式、租金服务的
      tempPickerViewValue: {
        area: ['area', 'null'],
        mode: ['null'],
        price: ['null']
      },
      // 为筛选服务的
      tempMoreValue: [],
      houseCondition: null // 房屋筛选的条件
    }
  }

  types = [
    {
      type: 'area',
      name: '区域'
    },
    {
      type: 'mode',
      name: '方式'
    },
    {
      type: 'price',
      name: '租金'
    },
    {
      type: 'more',
      name: '筛选'
    }
  ]

  /**
   * 我们最终是要看 selectValue 选中的值，来决定我们的高亮状态(selectedTypeTitle)
   * 产品经理此处的约定就是 只要selectValue它的值不是默认值，那就高亮
   */
  dealWithHighLight = () => {
    const { selectValue } = this.state
    let tempObj = {}
    Object.keys(selectValue).forEach(item => {
      if (item === 'area') {
        tempObj['area'] =
          selectValue.area.length >= 2 && selectValue.area[1] !== 'null'
      } else if (item === 'mode') {
        tempObj['mode'] =
          selectValue.mode.length > 0 && selectValue.mode[0] !== 'null'
      } else if (item === 'price') {
        tempObj['price'] =
          selectValue.price.length > 0 && selectValue.price[0] !== 'null'
      } else if (item === 'more') {
        tempObj['more'] = selectValue.more.length > 0
      }
    })

    this.setState({
      selectedTypeTitle: tempObj
    })
  }

  getHouseConditionData = async () => {
    const { value } = await getCurrentCity()
    const res = await getHouseCondition(value)

    this.setState({
      houseCondition: res.data.body
    })
  }

  componentDidMount () {
    this.getHouseConditionData()
  }

  clickType = type => {
    const { selectedTypeTitle } = this.state
    this.setState({
      openType: type,
      selectedTypeTitle: {
        ...selectedTypeTitle,
        [type]: true
      }
    })
  }

  // 类型标题部分
  renderTypeTitle = () => {
    const { selectedTypeTitle } = this.state
    return (
      <Flex className={styles.filterTitle}>
        {this.types.map(item => {
          // 决定遍历到的item这一项是否高亮显示
          const isSelect = selectedTypeTitle[item.type]

          return (
            <Flex.Item key={item.type}>
              <span
                className={classNames(styles.dropdown, {
                  [styles.selected]: isSelect
                })}
                onClick={() => this.clickType(item.type)}
              >
                <span>{item.name}</span>
                <i className='iconfont icon-arrow' />
              </span>
            </Flex.Item>
          )
        })}
      </Flex>
    )
  }

  cancelMask = () => {
    this.setState(
      {
        selectedTypeTitle: {
          [this.state.openType]: false
        }
      },
      () => {
        this.setState(
          {
            openType: ''
          },
          () => {
            this.dealWithHighLight()
          }
        )
      }
    )
  }

  // 渲染遮罩
  renderMask = () => {
    const { openType } = this.state
    const isShow =
      openType === 'area' || openType === 'mode' || openType === 'price'

    /**
    if (!isShow) return null

    return <div onClick={this.cancelMask} className={styles.mask}></div>
     */
    return (
      <Spring to={{ opacity: isShow ? 1 : 0 }} config={{ duration: 250 }}>
        {props => {
          if (props.opacity === 0) {
            return null
          }
          return (
            <div
              onClick={this.cancelMask}
              style={{ opacity: props.opacity }}
              className={styles.mask}
            ></div>
          )
        }}
      </Spring>
    )
  }

  onChange = value => {
    const { tempPickerViewValue, openType } = this.state

    this.setState({
      tempPickerViewValue: {
        ...tempPickerViewValue,
        [openType]: value
      }
    })
  }

  // 渲染PickerView
  renderPickerView = () => {
    const {
      openType,
      tempPickerViewValue,
      selectValue,
      houseCondition: { area, subway, rentType, price }
    } = this.state

    let data = null
    let cols = 3

    switch (openType) {
      case 'area':
        data = [area, subway]
        cols = 3
        break

      case 'mode':
        data = rentType
        cols = 1
        break
      case 'price':
        data = price
        cols = 1
        break

      default:
        break
    }

    // 取出设置好的值，然后设置给PickerView的value即可
    const value = tempPickerViewValue[openType]

    return (
      <div>
        <PickerView
          data={data}
          cols={cols}
          value={value}
          onChange={this.onChange}
        />
        <FilterFooter
          onCancel={() => this.cancelMask()}
          onOk={() => {
            this.setState(
              {
                selectValue: {
                  ...selectValue,
                  [openType]: tempPickerViewValue[openType]
                }
              },
              () => {
                this.setState(
                  {
                    openType: ''
                  },
                  () => {
                    // 对状态做最后一次高亮的处理
                    this.dealWithHighLight()

                    // 把我们最终的值传递给父组件
                    this.props.onConditionChange(this.state.selectValue)
                  }
                )
              }
            )
          }}
        />
      </div>
    )
  }

  toggleSelect = value => {
    let oldTempMoreValue = this.state.tempMoreValue

    if (oldTempMoreValue.includes(value)) {
      // 之前有
      oldTempMoreValue = oldTempMoreValue.filter(item => item !== value)
    } else {
      // 之前没有
      oldTempMoreValue.push(value)
    }

    this.setState({
      tempMoreValue: oldTempMoreValue
    })
  }

  renderEveryItem = (title, data) => {
    const { tempMoreValue } = this.state
    return (
      <>
        <dt className={styles.dt}>{title}</dt>
        <dd className={styles.dd}>
          {data.map(item => {
            return (
              <span
                key={item.value}
                className={classNames(styles.tag, {
                  [styles.tagActive]: tempMoreValue.includes(item.value)
                })}
                onClick={() => this.toggleSelect(item.value)}
              >
                {item.label}
              </span>
            )
          })}
        </dd>
      </>
    )
  }

  renderMoreView = () => {
    const {
      roomType,
      oriented,
      floor,
      characteristic
    } = this.state.houseCondition
    const { selectValue, tempMoreValue } = this.state
    return (
      <div className={styles.filterMore}>
        <div
          className={styles.filterMoreMask}
          onClick={() => this.cancelMask()}
        ></div>
        <div className={styles.tags}>
          <dl className={styles.dl}>
            {/* 户型 */}
            {this.renderEveryItem('户型', roomType)}
            {/* 朝向 */}
            {this.renderEveryItem('朝向', oriented)}
            {/* 楼层 */}
            {this.renderEveryItem('楼层', floor)}
            {/* 房屋亮点 */}
            {this.renderEveryItem('房屋亮点', characteristic)}
          </dl>
        </div>
        <div className={styles.filterMoreFooter}>
          <FilterFooter
            cancelText='清除'
            onCancel={() => {
              this.setState({
                tempMoreValue: []
              })
            }}
            onOk={() => {
              this.setState(
                {
                  selectValue: { ...selectValue, more: tempMoreValue }
                },
                () => {
                  this.setState(
                    {
                      openType: ''
                    },
                    () => {
                      this.dealWithHighLight()

                      // 把我们最终的值传递给父组件
                      this.props.onConditionChange(this.state.selectValue)
                    }
                  )
                }
              )
            }}
          />
        </div>
      </div>
    )
  }

  render () {
    const { houseCondition, openType } = this.state
    return (
      <div className={styles.root}>
        {this.renderMask()}
        <div className={styles.content}>
          {/* 渲染标题 */}
          {this.renderTypeTitle()}
          {/* 渲染PickerView */}
          {houseCondition &&
            (openType === 'area' ||
              openType === 'mode' ||
              openType === 'price') &&
            this.renderPickerView()}
          {/* 渲染右边的MoreView */}
          {houseCondition && openType === 'more' && this.renderMoreView()}
        </div>
      </div>
    )
  }
}
